$.extend({
	getHostUrl : function() {
		return window.location.protocol + "//" + window.location.host;
	},
	getHostName : function() {
		var pathname = window.location.pathname;
		return pathname = pathname.substring(0, pathname.indexOf("/", 1) + 1);
	},
	getBaseHref : function() {
		return $.getHostUrl() + $.getHostName();
	},
	getBaseHerf : function() {
		return $.getHostUrl() + $.getHostName();
	},
	getNowHref : function() {
		return $.getHostUrl() + window.location.pathname;
	},
	getLocalDataUrl : function() {
		return window.location.href.replace(/^(\#\!)?\#/, '');
	},
	/**
	 * @ 获取Cookie的值 @ cookieName cookie变量名
	 */
	getCookie : function(cookieName) {
		var getC = document.cookie, reg = new RegExp(cookieName + "=([^;]*)");
		var val = '';
		if (reg.test(getC)) {
			val = RegExp.$1;
		}
		if(val == '\"\"'){
			return '';
		}
		return val;
	},
	/**
	 * @ 计算毫秒，返回毫秒数 @ temer 要计算的字符串
	 */
	getDates : function(temer) {
		// var timeSize = [ "s", "m", "h", "D", "W", "M", "Y" ];
		// var tl = temer.length;
		var str = {};
		var s = 24 * 60 * 60;
		var sum = 0;
		var arra = temer.match(/\d+\w/g);
		if (arra == null)
			return false;
		for (var i = 0, l = arra.length; i < l; i++) {
			new RegExp("^(\\d+)([a-z]+)$", "i").test(arra[i]);
			str[RegExp.$2] = RegExp.$1;
		}
		if (str.s)
			sum = +str.s;
		if (str.m)
			sum += +str.m * 60;
		if (str.h)
			sum += +str.h * 60 * 60;
		if (str.D)
			sum += +str.D * s;
		if (str.W)
			sum += +str.W * s * 7;
		if (str.M)
			sum += +str.M * s * 30;
		if (str.Y)
			sum += +str.Y * s * 365;
		return sum * 1000;
	},
	/**
	 * @ 设置Cookie的方法 @ cookieName Cookie的名字 @ cookieInfo 参数是Cookie内容和要设置的时间
	 */
	setCookie : function(cookieName, cookieInfo) {
		var str = [];
		// 判断参数类型
		if (typeof cookieInfo == "string") {
			str = cookieInfo;
		} else {
			if (typeof cookieInfo.values == "object") {
				for ( var o in cookieInfo.values) {
					str.push(o + "=" + cookieInfo.values[o] + "&");
				}
				str = str.join("").slice(0, -1);
			} else {
				str = cookieInfo.values;
			}
		}
		// 判断时间的存在
		if (cookieInfo.temer) {
			var d = $.getDates(cookieInfo.temer);
			document.cookie = cookieName + "=" + str + ";expires="
					+ new Date(new Date().getTime() + d).toGMTString();
		} else
			document.cookie = cookieName + "=" + str;
	},
	/**
	 * @ 删除Cookie的方法 @ cookieName Cookie的名字
	 */
	delCookie : function(cookieName) {
		var getC = document.cookie, reg = new RegExp(cookieName + "=[^;]?");
		if (reg.test(getC))
			document.cookie = cookieName + "=;expires="
					+ new Date(-1).toGMTString();
	}
});


function GetQueryString(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

var _r = GetQueryString('_r');
if(_r){
	$.setCookie("_r",_r);
}

var _p = GetQueryString('_p');
if(_p){
	$.setCookie("_p",_p);
}

var _oemId = GetQueryString('_oemId');
if(_oemId){
	$.setCookie("_oemId",_oemId);
}

var SYS_AGENT_ID = "2015000000";
/**
 * 判断是否是OEM
 * @returns {Boolean}
 */
function isOem(){
	var id = $.getCookie('_oemId');
	if(id && id != SYS_AGENT_ID){
		return true;
	}else{
		return false;
	}
}

/**
 * 右下角弹窗
 */
var alertMsg = {
	num : 1,
	closeTime : 8000,// 自动关闭延时时间(毫秒)
	fadeTime : 1000,// 出入场动画时间(毫秒)
	alert : function(title, msg, level, position) {
		var option = {
			title : title,
			msg : msg,
			position : position || 'right-bottom'
		};
		var $alert = {};
		switch (level) {
		case "correct":// 成功
			$alert = this.correct(option);
			break;
		case "success":// 成功
			$alert = this.success(option);
			break;
		case "error":// 错误
			option['position'] = position || 'center-center';// 错误提示默认居中
			option['mask'] = true;// 错误框默认添加遮罩层
			$alert = this.error(option);
			break;
		case "info":// 普通信息
			$alert = this.info(option);
			break;
		case "warn":// 警告
			option['mask'] = true;// 警告框框默认添加遮罩层
			$alert = this.warn(option);
			break;
		default:// 默认为普通提示
			$alert = this.info(option);
			break;
		}

		return $alert;

	},
	success : function(option) {
		return correct(option);
	},
	correct : function(option) {// 成功提示框
		if (option != undefined) {
			if (typeof option === "string") {
				option = {
					msg : option
				};
			}
		} else {
			option = {};
		}
		if (!option['title']) {
			option['title'] = "成功";
		}
		if (!option['msg']) {
			option['msg'] = "操作成功!";
		}
		option['title'] = '<i class="ace-icon fa fa-check"></i>'
				+ option['title'];
		option['level'] = 'success';
		return this.show(option);
	},
	error : function(option) {// 错误提示框
		if (option != undefined) {
			if (typeof option === "string") {
				option = {
					msg : option
				};
			}
		} else {
			option = {};
		}
		if (!option['title']) {
			option['title'] = "错误";
		}
		if (!option['msg']) {
			option['msg'] = "操作失败!";
		}
		option['title'] = '<i class="ace-icon fa fa-times"></i>'
				+ option['title'];
		option['level'] = 'danger';
		return this.show(option);
	},
	info : function(option) {// 信息提示框
		if (option != undefined) {
			if (typeof option === "string") {
				option = {
					msg : option
				};
			}
		} else {
			option = {};
		}
		if (!option['title']) {
			option['title'] = "提示";
		}
		if (!option['msg']) {
			option['msg'] = "操作提示！";
		}
		option['level'] = 'info';
		return this.show(option);
	},
	warn : function(option) {// 警告提示框
		if (option != undefined) {
			if (typeof option === "string") {
				option = {
					msg : option
				};
			}
		} else {
			option = {};
		}
		if (!option['title']) {
			option['title'] = "警告!";
		}
		if (!option['msg']) {
			option['msg'] = "操作警告！";
		}
		option['level'] = 'warning';
		return this.show(option);
	},
	confirm : function(option, msg, call) {
		var op = {
			level : 'confirm',
			call : null
		};
		// 如果option为string类型，将参数依次作为title、msg、callback处理，否则认为是所有参数的对象
		if (typeof option === 'string') {
			option = {
				title : option,
				msg : msg,
				call : call
			};
		}
		option['mask'] = option['mask'] || true;// 默认打开遮罩层
		option['close'] = 'false';// 不自动关闭
		$.extend(op, option);
		return this.show(op);
	},
	getBox : function() {
		var $box = $('#rightFootMsgBox');
		if ($box.length === 0) {
			$("body")
					.append(
							'<div id="rightFootMsgBox" class="rightFootMsgBox"><div class="tool" ><button type="button" class="close"><i class="ace-icon fa fa-times"></i></button></div></dvi>');
			$box = $('#rightFootMsgBox');
			$box.children(".tool").children(".close").on('click',
					alertMsg.closeAll);
		}
		return $box;
	},
	show : function(op) {
		this.init();
		return this.create(op);
		;
	},
	close : function(obj) {
		alertMsg.init();// 消息全部关闭按钮显示/隐藏
		if(obj){
			$(obj).fadeOut(this.fadeTime, function() {
				alertMsg.destroy(obj);
			});
		}
		return this;
	},
	closeById : function(id) {
		this.close($("#" + id));
	},
	closeAll : function() {
		alertMsg.getBox().fadeOut(this.fadeTime, function() {
			alertMsg.getBox().remove();
		});
	},
	callBack : function(v, fn) {
		if (typeof fn === 'function') {
			fn(v);
		}
	},
	create : function(option) {
		var isConfirm = 0;
		if (option['level'] === 'confirm') {
//			option.level = 'info';
			isConfirm = 1;
		}
		var alertMsgId = option.id;// 支持自定义ID
		if (!alertMsgId) {
			this.num = this.num + 1;
			alertMsgId = "alertMsgId" + this.num;
		}
		var html = '';
		var $alert = {};

		var op_mask = option['mask'] || false;
		var $mask = null;
		if(op_mask){//如果有遮罩层的，都到中间打开
			var class_name = '';
			var alt_level = option['level'];
			switch (alt_level) {
			case "info" :
				alt_level = "confirm";
			case "confirm":
				html = '<div class="alert-btn-box"><button class="btn btn-xs btn-yellow ok" type="button">确定</button><button class="btn btn-xs btn-yellow cancel" type="button" >取消</button></div>';
				class_name = "gritter-warning gritter-center alert-confirm";
				break;
			case "warning":
				html = '<div class="alert-btn-box"><button class="btn btn-xs btn-yellow ok" type="button">确定</button></div>';
				class_name = "gritter-warning gritter-center alert-confirm";
				break;
			case "danger" :
				alt_level = "error";
			case "error" :
				html = '<div class="alert-btn-box"><button class="btn btn-xs btn-pink ok" type="button">确定</button></div>';
				class_name = "gritter-error gritter-center alert-confirm";
				break;
			default:
				return null;
			}
			$.gritter.add({
				title:option.title,
				text:option.msg,
				class_name:class_name,
				sticky:true,//不自动关闭
				bottom:html
			});
				
			$mask = mask.show();//开启遮罩
			var ok = false;
			$alert = $('.alert-confirm');
			mask.onTopOf($mask, $alert);//弹出错误提示框在当前遮罩层之上
			var $closeIcon = $('.gritter-close',$alert).on('click',function(){
				alertMsg.callBack(ok, option.call);
				if($mask){
					mask.hide($mask);
				}
			});
			$('.alert-btn-box > .ok').on('click',function(){
				ok = true;
				$closeIcon.trigger('click');
			});
			$('.alert-btn-box > .cancel').on('click',function(){
				ok = false;
				$closeIcon.trigger('click');
			});
			
			return $alert;
			
		}
		html += '<div class="alert alert-' + (option.level || 'info')
				+ '" id="' + alertMsgId + '">';
		html += '	<button type="button" class="close"><i class="ace-icon fa fa-times"></i></button>';
		html += '	<div class="title"><strong>' + option.title
				+ '</strong></div>';
		html += '	<div class="message">' + option.msg + '</div>';
	// if(isConfirm === 1){
	// html+=' <div class="align-right alert-btn-box"><button class="btn
	// btn-xs" type="button">确定</button><button class="btn btn-xs"
	// type="button">取消</button></div>';
		html += '</div>';
		var $alertBox = this.getBox().append(html);

		$alert = $("#" + alertMsgId);

//		if (isConfirm === 1) {
//			var $btnBox = $alert
//					.append(' <div class="align-right alert-btn-box"><button class="btn btn-xs" type="button">确定</button><button class="btn btn-xs" type="button">取消</button></div>');
//			var height = parseFloat($alert.css("height"));
////			var $btnBoxHeight = parseFloat($('.alert-btn-box > button', $alert).css(
////					"height"));
////			alert($('.alert-btn-box > button:eq(0)', $alert).css(
////			"width"));
//			$alert.css('height', (height + 10) + 'px');
//			$('.alert-btn-box > button', $btnBox).css("margin-right","5px");
//		}
		
		//提示框位置设置
//		var position = option.position;
//		var posLevel  = '';//水平布局
//		var posVertical = '';//垂直布局
//		if(position){
//			//水平、垂直两个布局属性
//			if(position.indexOf("-") != -1){
//				var posArray = position.split("-");
//				posLevel = posArray[0];
//				posVertical = posArray[1];
//			}else{//只有一个布局属性的让两个相等
//				posLevel = position;
//				posVertical = position;
//			}
//			
//			$alert.addClass("position-level-" + posLevel);
//			$alert.addClass("position-vertical-" + posVertical);
//		}
//		$alertBox.addClass("full-screen");
		

		$(".close", $alert).on('click', function() {
			$alert.trigger("close");
		});
		// 渐入显示
		$alert.fadeIn(option.time || this.fadeTime);
		var closeType = option.close || 'auto';
		// 自动关闭
		if (closeType === 'auto' || closeType === 'true') {
			var at_time = option.time || this.closeTime;
			setTimeout(function() {
				$alert.trigger("close");
			}, at_time);
		}
		// }


		$alert.on('close', function() {
			if (op_mask === true || op_mask === 'true') {
				mask.hide($mask);
			}
			alertMsg.close($alert);
		});

		return $alert;
	},
	destroy : function(obj) {
		$(obj).remove();
		return this;
	},
	init : function() {
		var $box = this.getBox();
		// 如果弹出层个数超过5个，显示“关闭所有”按钮
		if ($box.children(".alert").length >= 5) {
			$box.children(".tool").children(".close").show();
		} else {
			$box.children(".tool").children(".close").hide();
		}
		return this;
	}
};


// 对象copy
var msg = alertMsg;
$.extend(msg, alertMsg);

function getFormParams($form) {
	var $form = $($form);// 查询条件表单
	var search_param = {};
	if (!$form || $form.length !== 1) {
		return search_param;
	}
	var search_param_array = $form.serializeArray();// 获取条件参数列表
	// data.push({name:"reqType",value:"ajax"});
	// 处理 Switch 取值异常问题
	var $input_switch = $('input.ace-switch', $form);// 获取表单中 switch
	// 的input元素列表
	$input_switch.each(function() {
		var $input = $(this);
		var p_name = $input.attr('name');
		var p_value = $input.val();
		var isExist = false;
		// 遍历序列号的表单参数中是否包含了该元素
		$(search_param_array).each(function(i) {
			// 如果存在了，则不处理
			if (this.name === p_name) {
				isExist = true;
				// 退出本次循环
				return false;
			}
		});
		// 如果没有，则加入到参数列表
		if (!isExist) {
			search_param_array.push({
				name : p_name,
				value : p_value
			});
		}
	});
	// search_param = search_param_array;
	$(search_param_array).each(
			function() {
				if ($form.attr('method')
						&& $form.attr('method').toUpperCase() !== 'POST') {
					search_param[this.name] = encodeURI(this.value);
				} else {
					search_param[this.name] = encodeURI(this.value);;
				}
			});
	// if($form.attr('method') && $form.attr('method').toUpperCase() !==
	// 'POST'){
	// $(search_param_array).each(function(){
	// search_param[this.name] = encodeURI(this.value);
	// });
	// }

	return search_param;
}

var forwardByRspCode = {
	"099999" : function (json){
		//跳转到登录
		if(typeof toLoginPage === 'function'){
			toLoginPage();
			return false;
		}
		return true;
	},
	"099998" : function (json){
		//跳转到首页
		if(typeof toIndexPage === 'function'){
			toIndexPage();
			return false;
		}
		return true;
	},
	"000232" : function (json){
		//跳转到实名认证
		var r = confirm(json["RSPMSG"]);
		if(r){
			openUrl(BASE_PATH + "user/user_certification.jsp");
			return false;
		}
		return false;
	},
	"000861" : function (json){
		//跳转到激活(绑定合作商)
		var r = confirm(json["RSPMSG"]);
		if(r){
			openUrl(BASE_PATH + "user/user_activates.jsp");
			return false;
		}
		return false;
	},
	"000240" : function (json){
		//跳转到银行卡认证
		var r = confirm(json["RSPMSG"]);
		if(r){
			openUrl(BASE_PATH + "user/user_card_binding.jsp");
			return false;
		}
		return false;
	}
};

function formSubmitForAjax(opt, $form) {
	if($form && $($form).attr('mask') == 'true'){
		mask.loading();
	}
	$.ajax({
		type : opt.method || 'POST',
		url : opt.url,
		data : opt.data,
		dataType : opt.dataType || "json",
		cache : false,
		success : function(result) {
			try {
				mask.loaded();
				result = result['REP_BODY'];
				if(typeof forwardByRspCode[result['RSPCOD']] === 'function'){
					if(!forwardByRspCode[result['RSPCOD']](result)){
						return false;
					}
				}
				/*if(result['RSPCOD'] === '099999'){// 请登录
					if(typeof toLoginPage === 'function'){
						toLoginPage();
						return false;
					}
				}else if(result['RSPCOD'] === '099998'){// 到主页
					if(typeof toIndexPage === 'function'){
						toIndexPage();
						return false;
					}
				}*/
			} catch (e) {
				
			}
			
			if (typeof opt.success === 'function') {
				opt.success(result, $form);
			} else {
				AjaxDone(result, $form);
			}
		},
		error : opt.error || function() {
			alert("请求失败!")
			try {
				mask.loaded();
			} catch (e) {
			}
		}
	});
}

function formSubmitToGetUrl($form){
	$form = $($form);
	var url = $form.attr('action');
	var data = getFormParams($form);
	var idx = -1;
	//没有问号"?"
	if( (idx = url.indexOf('?')) < 0){
		url += '?';
	}
	var i = 0;
	jQuery.each(data, function(key, val) { 
		url += "&" + key + "=" + encodeURI(val);
	}); 
	openUrl(url);
	return false;
}

/**
 * 表单验证并且在验证通过后提交到服务器
 * 
 * @param form
 *            表单对象
 * @param callback
 *            回调函数
 * @returns {Boolean}
 */
function validateCallback(form, callback) {
	var $form = $(form);
	if (TDValidateForm($form)) {
		var param = {};
		// 在base.js中定义了getFormParams 来获取表单的参数列表,由该方法处理左右切换开关取值问题
		if (typeof getFormParams === 'function') {
			param = getFormParams($form);
		} else {
			param = $form.serializeArray();
		}
		var opt = {
			method : $form.attr('method'),
			url : $form.attr("action"),
			data : param,
			dataType : "json",
			success : callback
		};
		formSubmitForAjax(opt, $form);
		return false;
	} else {
		return false;
	}

}

/**
 * 对话框ajax回调
 * 
 * @param result
 *            返回结果集
 * @param $form
 *            提交的表单(可根据当前表单定位到哪个对话框)
 */
function AjaxDone(result,$form) {
// var code = result.rspcod;
// var type = result.callBackType;
	if (result.RSPCOD != "000000") {// 失败
		
	} else {
		
	}
}

/**
 * 填充表单
 * 
 * @param form
 *            表单对象
 * @param data
 *            表单数据
 */
/*function fillForm(form, data) {
	var $form = $(form);
	var $data = data || {};
	var value, tagName, type, arr;
	for ( var key in $data) {
		value = $data[key];
		$(
				"[name='" + key + "'],[name='" + key + "_dict'],[name='" + key
						+ "[]']", $form).each(function(i) {
			tagName = $(this)[0].tagName;
			type = $(this).attr('type');
			if (tagName == 'INPUT') {
				if (type == 'radio') {
					$(this).attr('checked', $(this).val() == value);
				} else if (type == 'checkbox') {
					if (value && value.indexOf(",") != -1) {
						arr = value.split(',');
					} else {
						arr = [ value ];
					}
					for (var i = 0; i < arr.length; i++) {
						// 开启/关闭 两项按钮用的checked，给该元素复制达到选中的默认状态
						if ($(this).filter('.ace-switch').length == 1) {
							$(this).attr('value', arr[i]);
						} else if ($(this).val() == arr[i]) {
							$(this).attr('checked', true);
							break;
						}
					}
				} else {
					var code = $(this).attr('dict');
					value = initFormat($(this), value);
					// init-format
					if (code != undefined && code != "") {
						$(this).val(DICT.get(code, value));
					} else {
						$(this).val(value);
					}

				}
			} else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
				// alert(value);
				$(this).val(value);
				if (tagName == 'TEXTAREA') {
					$(this).html(value);
				}
				$(this).attr('defVal', value);
			} else {
				$(this).attr('value', value);
			}

		});
	}
}*/

/**
 * 填充表单
 * @param form 表单对象
 * @param data 表单数据
 */
function fillForm(form, data) {
	
	var $form = $(form);
	var $data = data || {};
	var value, tagName, type, arr;
	for (var key in $data) {
		value = $data[key];	
		$("[name='" + key + "'],[name='" + key + "_dict'],[name='" + key + "[]']", $form).each(function(i) {			
			tagName = $(this)[0].tagName;
			type = $(this).attr('type');
			if (tagName == 'INPUT') {
				if (type == 'radio') {
					$(this).attr('checked', $(this).val() == value);
				} else if (type == 'checkbox') {
					if(value && value.indexOf(",") != -1){
						arr = value.split(',');
					}else{
						arr = [value];
					}
					for (var i = 0; i < arr.length; i++) {
						//开启/关闭 两项按钮用的checked，给该元素复制达到选中的默认状态
						if($(this).filter('.ace-switch').length == 1){
							$(this).attr('value',arr[i]);
						}else if ($(this).val() == arr[i]) {
							$(this).attr('checked', true);
							break;
						}
					}
				} else {				
					var code = $(this).attr('dict');
					var fmt = $(this).attr('init-format');
					if(fmt){
						try {
							fmt = fmt.replaceAll("{value}",value);
							value = eval('(' + fmt + ')');
						} catch (e) {						
						}
					}
					if(code != undefined && code != ""){
						$(this).val(DICT.get(code, value));
					}else{
						$(this).val(value);
					}
				}
			} else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
				$(this).val(value);
				
				var code = $(this).attr('dict');
				var fmt = $(this).attr('init-format');
				if(fmt){
					try {
						fmt = fmt.replaceAll("{value}",value);
						value = eval('(' + fmt + ')');
					} catch (e) {						
					}
				}
				if(code != undefined && code != ""){
					value = DICT.get(code, value);
				}
				
				if(tagName == 'TEXTAREA'){
					$(this).html(value);
				}
				$(this).attr('defVal',value);
			}else{
				$(this).attr('value',value);
			}

		});
	}
}

function fillTable($table, data) {
	var $table = $($table);
	jQuery.each(data, function(k, v) {
		// alert($("td[valueOf*='{"+k+"}']").length);
		$("*[valueOf*='{" + k + "}']", $table).each(function() {
			var $td = $(this);
//			if(k == 'CUST_LEVEL'){
//				
//				alert($td.attr('init-format'));
//			}
			var valueOf = $td.attr("valueOf");
			var val = initFormat($td, v);
			if(!val){
				val = "";
			}
			valueOf = valueOf.replace("{" + k + "}", val);
			$td.html(valueOf);
		});
	});
}

/**
 * 提供字符串全部替换的方法
 */
String.prototype.replaceAll = function(s1, s2) {
	return this.replace(new RegExp(s1, "gm"), s2);
}

function initFormat($elm, value) {
	var fmt = $($elm).attr('init-format');
	if (fmt) {
		try {
			fmt = fmt.replaceAll("{value}", value);
//			 alert(fmt);
			value = eval('(' + fmt + ')');
		} catch (e) {

		}
	}
	return value;
}

function getJsonDataByName(json, dataName) {
	var fData = {};
	if (typeof json === 'string') {
		json = eval('(' + json + ')');
	}
	if (dataName && typeof dataName === 'string') {
		if (dataName.indexOf(',') > 0) {// 多个属性合并
			var p_list = dataName.split(',');

			for (var j = 0; j < p_list.length; j++) {
				var dName = p_list[j];
				if (TD.isEmpty(dName)) {
					continue;
				}

				fData = $.extend({}, fData, getJsonDataByName(json, dName));
			}
			return fData;
		}

		if (dataName.indexOf('.') > 0) {// 参数嵌套
			var p_array = dataName.split('.');
			var d = json;
			for (var i = 0; i < p_array.length; i++) {
				if (typeof d === 'string') {
					d = eval('(' + d + ')');
				}
				d = d[p_array[i]] || {};
			}
			fData = d || {};
		} else {
			fData = json[dataName] || {};
		}

	} else {
		fData = json;
	}
	// //如果没找到，在属性名称前面加一个obj，默认去obj下面取
	// if(!fData){
	// if(dataName && dataName.indexOf("obj") != 0){
	// dataName = "obj." + dataName;
	// }else{
	// dataName = "obj";
	// }
	// return getJsonDataByName(json,dataName);
	// }
	return fData;
}

/**
 * 验证表单 属性说明: validate="true" 需要验证 msg="错误时提示信息" datatype="数据类型"
 * 
 * 
 */
function TDValidateForm($form) {
	var bool = true;
	var dmsg = "该字段不能为空!";
	var tmsg = null;
	var $id = null;
	var $datatype = null;
	var area = "input[type=text],input[type=email],input[type=password]";
	$(area, $form).each(
			function() {
				bool = true;
				tmsg = null;
				$id = null;
				$datatype = null;
				$id = $(this);

				if ($id.attr('RegExp') && $id.attr('validate') != "false") {
					var reg = eval('(' + $id.attr('RegExp') + ')');
					// alert($id.val());
					// alert(reg.test(1234));
					if (!reg.test($id.val())) {
						TDTips($id, $id.attr('tips') ? $id.attr('tips')
								: '格式错误');
						bool = false;
						return bool;
					}
				}

				if ($id.attr('validate') == 'true') {
					if ($id.attr('msg') != undefined && $id.attr('msg') != "") {
						tmsg = $id.attr('msg');
					}
					if ($id.val() === undefined || $.trim($id.val()) === ""
							|| $id.val() == $id.attr('placeholder')) {

						TDTips($id, tmsg == null ? dmsg : tmsg);
						bool = false;
						return bool;
					} else {// 正则表达式效验
						$datatype = $.trim($id.attr('datatype'));
						if ($datatype != undefined && $datatype != "") {
							if ($datatype == "email") {
								if (!regexObj.email($id.val())) {
									TDTips($id, tmsg == null ? regexMsg.email
											: tmsg);
									bool = false;
									return bool;
								}
							} else if ($datatype == "url") {
								// return true;
							} else if ($datatype == "number") {
								if (!regexObj.number($id.val())) {
									TDTips($id, tmsg == null ? regexMsg.number
											: tmsg);
									bool = false;
									return bool;
								}
							} else if ($datatype == "date") {
								// return true;
							} else if ($datatype == "datetime") {
								// return true;
							} else if ($datatype == "money") {
								if (!regexObj.money($id.val())) {
									TDTips($id, tmsg == null ? regexMsg.money
											: tmsg);
									bool = false;
									return bool;
								}
							} else if ($datatype == "mobile") {
								if (!regexObj.mobile($id.val())) {
									TDTips($id, tmsg == null ? regexMsg.mobile
											: tmsg);
									bool = false;
									return bool;
								}
							} else if ($datatype == "chinese") {
								if (!regexObj.chinese($id.val())) {
									TDTips($id, tmsg == null ? regexMsg.chinese
											: tmsg);
									bool = false;
									return bool;
								}
							} else if ($datatype == "idcard") {
								if (!regexObj.idcard($id.val())) {
									TDTips($id, tmsg == null ? regexMsg.idcard
											: tmsg);
									bool = false;
									return bool;
								}
							} else if ($datatype == "notempty") {
								if (!regexObj.notempty($id.val())) {
									TDTips($id,
											tmsg == null ? regexMsg.notempty
													: tmsg);
									bool = false;
									return bool;
								}
							} else if ($datatype == "word") {
								if (!regexObj.word($id.val())) {
									TDTips($id, tmsg == null ? regexMsg.word
											: tmsg);
									bool = false;
									return bool;
								}
							} else {
								// return true;
							}
						}
					}
				}
			});
	if (bool) {
		return true;
	} else {
		return false;
	}

}
/**
 * 提示
 * 
 * @param $id
 *            校验对象
 * @param tmsg
 *            提示信息
 */
function TDTips($id, tmsg) {
	$id.tips({
		side : 3,
		msg : tmsg,
		bg : '#E3C94C',
		time : 2
	});
	$id.focus();
}

/**
 * 日期格式化
 */
function dateFormat(sdate) {
	var tmpDate;
	if (sdate == null || sdate.length != 14) {
		return "";
	}
	tmpDate = sdate.substring(0, 4) + "-";
	tmpDate = tmpDate + sdate.substring(4, 6) + "-";
	tmpDate = tmpDate + sdate.substring(6, 8) + " ";
	tmpDate = tmpDate + sdate.substring(8, 10) + ":";
	tmpDate = tmpDate + sdate.substring(10, 12) + ":";
	tmpDate = tmpDate + sdate.substring(12, 14);

	return tmpDate;
}

/**
 * 每次都会打开一个遮罩层，所以多个dialog打开并关闭一个时，遮罩层不会全部消失
 */
var mask = {
	idNum : 0,
	show : function() {
		this.idNum = this.idNum + 1;
		var maskId = 'mask_' + this.idNum;
		// if(!$(".mask") || $(".mask").length <= 0){
		var html = '<div id="' + maskId + '" class="mask"></div>';
		$("body").append(html);
		// }
		$("body").css("overflow", "hidden").css({
			width : "100%",
			height : "100%"
		});
		var $mask = $("#" + maskId);
		// 遮罩层每次添加一个 z-index 都在上一个的基础上加上100
		$mask.css("z-index", 1000 + ($(".mask").length * 100));
		// alert($(".mask").last().css('z-index'));
		// alert($mask.css("z-index"));
		$mask.show();// 显示
		return $mask;
	},
	hide : function(obj) {
		this.close(obj);
	},
	close : function(obj) {
		if (obj) {// 如果是关闭指定mask
			$(obj).remove();
		} else {
			$(".mask").last().remove();// 没指定则关闭最后一个
		}
		var $maskAll = $(".mask");
		if ($maskAll.length == 0) {// 所有遮罩层都关闭了才放出body的滚动条
			$("body").css("overflow", "");
		}
	},
	closeAll : function() {
		$(".mask").remove();
		$("body").css("overflow", "");
	},
	last : function() {
		return $(".mask").last();
	},
	zIndex : function(obj, zIdx) {
		if (!obj) {
			obj = $(".mask").last();
		}
		if (zIdx) {
			$(obj).css("z-index", zIdx);
			return zIdx;
		}
		return $(obj).css("z-index") || '1100';
	},
	onTopOf : function($mask, $obj) {
		if ($obj) {
			if (!$mask) {
				$mask = mask.last();
			}
			var zIdx = parseInt(mask.zIndex($mask));
			$obj = $($obj).css("z-index", zIdx + 1);
		}
	},
	loading : function(box,option){
		var $box = {};
		if(box){
			$box = $(box);
		}else{
			$box = $('.main-container');
		}
		$box.append('<div class="widget-box-overlay"><i class="ace-icon loading-icon fa fa-spinner fa-spin fa-2x white"></i></div>');
	},
	loaded : function(){
		$('.widget-box-overlay').remove();;
	}
};

function openUrl(url, type) {
	if (window.location == url) {
		return;
	}
	if (type == 1) {
		window.open(url);
	} else {
		window.location = url;
	}
}

var BASE_PATH = $.getBaseHref();

var SUCCESS_CODE = "000000";
function codeSuccess(json){
	try {
		if(SUCCESS_CODE == json["RSPCOD"]){
			return true;
		}
	} catch (e) {
		return false;
	}
	return false;
}

function doBtn($btn,state){
	$btn = $($btn);
	if(state == 1){
		$btn.removeAttr("disabled");
	}else{
		$btn.attr("disabled", "disabled");
	}
}

var URL_LOGIN_PAGE = "login.jsp";
var URL_INDEX_PAGE = "index.jsp";

/**
 * 跳转到登录页
 */
function toLoginPage(){
	openUrl(BASE_PATH + URL_LOGIN_PAGE);
}

/**
 * 跳转到首页
 */
function toIndexPage(){
	openUrl(BASE_PATH + URL_INDEX_PAGE);
}

function saveParamToPage($obj,data){
	if($obj && data){
		for ( var key in data) {
			$obj.attr(key,data[key]);
		}
	}
}

function getParamByPage($obj,key,def){
	return $obj.attr(key) || def;
}


function today(){
	var today=new Date();
    var h=today.getFullYear();
    var m=today.getMonth()+1;
    var d=1;
    var tag="";
    if(m<10){
    	 tag="0";
    }

//    return h+"-"+tag+m+"-"+"0"+d;
    return h+"-01-01";
}

function ytoday(){
	var today=new Date();
    var h=today.getFullYear();
    var m=today.getMonth()+1;
    var d=today.getDate();
    var tag="";
    var tag="0";
    if(m<10){
    	tag="0";
    }
    var _tag="";
    if(d<10){
    	_tag="0";
    }
    return h+"-"+tag+m+"-"+_tag+d;
}

/**
 * 判断客户端是否是PC(电脑)
 * @returns {Boolean}
 */
function IsPC() {
	var userAgentInfo = navigator.userAgent;
	var Agents = [ "Android", "iPhone", "SymbianOS", "Windows Phone"
	// , "iPad", "iPod"
	];
	var flag = true;
	for (var v = 0; v < Agents.length; v++) {
		if (userAgentInfo.indexOf(Agents[v]) > 0) {
			flag = false;
			break;
		}
	}
	return flag;
}

function IsWeiXin(){
	if (browser.versions.mobile) {//判断是否是移动设备打开。browser代码在下面
        var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
               return true;
        }
	} else {
	    //否则就是PC浏览器打开
		return false;
	}
}

var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {         //移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

function closeWindow() {
	if(IsWeiXin()){
		WeixinJSBridge.call('closeWindow');
	}else{
		window.opener = null;
		window.open(' ', '_self', ' '); 
		window.close();
	}
}

function createQrCode(opt) {
	var $box = opt["box"] || {};
	var data = opt['data'] || "";
	
	$box.qrcode(data);
}

/**
 * android/ios app与js通信接口
 * @param os
 * @param cmd
 * @param opt
 * @param data
 */
function appCallJsFunction(os,cmd,opt,data){
//	$("#show").html('app回调中::' + data);
//	$("#show").show();
//	alert("进入app回调");
//	alert("回调成功 os:" + os + ",cmd:" + cmd + ",opt:" + opt);
//	alert("图像数据:" + data);
	try {
		var fn = APP_CALL_MANAGE[cmd + ""] || {};
//		alert("fn:" + fn);
		if(typeof fn === "function"){
			fn(os,cmd,opt,data);
		}
	} catch (e) {
		
	}
}

/**
 * js 绑定 android/ios回调执行管理(根据cmd,绑定回调函数,由每个有需要的js继承并扩展此对象)
 */
var APP_CALL_MANAGE = {
	"0000" : function(os,cmd,opt,data){
		alert("绑定实例");
	}
};

function openMenu(menuArray){
	if(!menuArray){
		return;
	}
	var ran = parseInt(Math.random() * 100000);
	var boxId = "alert-menu-box-" + ran;
	$(document.body).append('<div id="'+boxId+'" class="alert-menu-box"></div>');
	var $box = $("#" + boxId);
	$box.html('');
	for (var i = 0; i < menuArray.length; i++) {
		var menu = menuArray[i];
		var id = menu['id'] || 'alert-menu-' + i;
		var html = '';
		html += '\
		<div id="'+id+'" class="alert-menu is-click">\
			<div class="alert-menu-text">'+ (menu['name'] || '') + '</div>\
		</div>';
		
		$box.append(html);
		
		$("#" + id).on("click",menu['click']);
	}
	//添加取消按钮
	$box.append('\
		<div id="sub-menu-close" class="alert-menu is-click">\
			<div class="alert-menu-text">取&nbsp;&nbsp;消</div>\
		</div>');
	$box.on("click",function(){
		$box.remove();
	});
	$box.show();
	return $box;
}

/**
 * 屏幕旋转事件
 */

// 判断屏幕是否旋转

//function orientationChange(event) {
//	alert(event);
//    switch(window.orientation) {
//
//    　　case 0:
//
////            alert("肖像模式 0,screen-width: " + screen.width + "; screen-height:" + screen.height);
//    	
//            break;
//
//    　　case -90:
//    	event.stopPropagation();
//    	event.cancelBubble = true;
////            alert("左旋 -90,screen-width: " + screen.width + "; screen-height:" + screen.height);
//
//            break;
//
//    　　case 90:   
//    	event.stopPropagation();
////            alert("右旋 90,screen-width: " + screen.width + "; screen-height:" + screen.height);
//
//            break;
//
//    　　case 180:   
//    	event.stopPropagation();
////        　　alert("风景模式 180,screen-width: " + screen.width + "; screen-height:" + screen.height);
//
//        　　break;
//
//    };};
//
//// 添加事件监听
//
//addEventListener('load', function(){
//    orientationChange();
//    window.onorientationchange = orientationChange;
//
//});

$(function(){
	$('.title-text-box').html($("title").html());
}); 
